package com.agent.user.service;

import cn.hutool.core.bean.BeanUtil;
import com.agent.common.constant.CommonConstants;
import com.agent.common.utils.FileUtils;
import com.agent.common.utils.IdGenerator;
import com.agent.user.dto.UserAssetRequest;
import com.agent.user.entity.UserAsset;
import com.agent.user.mapper.UserAssetMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
@RequiredArgsConstructor
public class UserAssetService {
    private final UserAssetMapper userAssetMapper;
    private final UserService userService;
    private final IdGenerator idGenerator = IdGenerator.getInstance();
    
    /**
     * 上传用户资产
     * @param userId 用户ID
     * @param file 上传的文件
     * @param baseStoragePath 基础存储路径
     * @return 资产ID
     * @throws IOException 文件操作异常
     */
    @Transactional
    public Long uploadUserAsset(Long userId, MultipartFile file, String baseStoragePath) throws IOException {
        // 验证用户是否存在
        if (userService.getUserById(userId) == null) {
            throw new IllegalArgumentException("User not found");
        }
        
        // 保存文件到存储
        String assetPath = FileUtils.saveUploadedFile(file, userId, baseStoragePath);
        
        // 记录资产信息
        UserAsset asset = new UserAsset();
        asset.setUserId(userId);
        asset.setAssetType(CommonConstants.ASSET_IMAGE); // 上传的都是图片
        asset.setAssetPath(assetPath);
        asset.setOriginalFilename(file.getOriginalFilename());
        asset.setIsUploaded(true);
        
        userAssetMapper.insert(asset);
        return asset.getId();
    }

    /**
     * 记录用户资产信息
     * @param request 用户ID
     */
    public boolean recordUserAsset(UserAssetRequest request) {
        UserAsset userAsset = BeanUtil.copyProperties(request, UserAsset.class);
        userAsset.setId(idGenerator.nextId());
        return userAssetMapper.insert(userAsset) > 0;
    }
}